const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const cors = require('cors');

const app = express();

// 启用 CORS
app.use(cors());

// 设置代理中间件
app.use('/api', createProxyMiddleware({
  target: 'http://localhost:6800', // Scrapyd 服务的地址
  changeOrigin: true,
  pathRewrite: {
    '^/api': '', // 重写路径，将 '/api' 替换为空
  },
  onProxyReq: (proxyReq, req, res) => {
    if (req.method === 'OPTIONS') {
      res.setHeader('Access-Control-Allow-Origin', '*');
      res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
      res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
      res.sendStatus(200);
    }
  },
  onProxyRes: (proxyRes, req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  }
}));

app.listen(3000, () => {
  console.log('        Proxy server is running on http://localhost:5000');
});
